package com.lilidp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lilidp.dto.LoginFormDTO;
import com.lilidp.dto.Result;
import com.lilidp.dto.UserDTO;
import com.lilidp.entity.User;
import com.lilidp.mapper.UserMapper;
import com.lilidp.service.IUserService;
import com.lilidp.utils.RedisConstants;
import com.lilidp.utils.RegexUtils;
import com.lilidp.utils.SystemConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.lilidp.utils.RegexUtils.isPhoneInvalid;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 栗顺
 
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //首先校验手机号
        boolean isvalid = isPhoneInvalid(phone);
        //手机号不符合
        if (isvalid) {
            return Result.fail("手机号格式错误");
        }
        //手机号符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        //将验证码保存并发送给用户
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY +phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
//        session.setAttribute("code",code);
        log.debug("验证码已发送成功，验证码：{}"+code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //校验一下手机号
        String phone = loginForm.getPhone();
        if(phone==null||RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误!");
        }
        //校验一下验证码
        String code = loginForm.getCode();
        if(code==null||code.length()!=6){
            return Result.fail("验证码格式错误!");
        }
        //从Redis中获取验证码,判断是否一致
        String code1 = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if(!code1.equals(code)){
            return Result.fail("验证码错误!");
        }
        //一致，根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //判断用户是否存在
        //不存在，创建新用户
        if(user==null){
            user=createUserWithPhone(phone);
        }
        //存在，登录成功
        //放入session信息

        String string = UUID.randomUUID().toString(true);
        //拷贝属性
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //设置值
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //设置属性
        String tokenKey=RedisConstants.LOGIN_USER_KEY+string;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        //设置过期时间
        stringRedisTemplate.expire(tokenKey,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //返回结果
        return Result.ok(string);
    }

    private User createUserWithPhone(String phone) {
        User user= new User().setPhone(phone)
                .setNickName(SystemConstants.USER_NICK_NAME_PREFIX +RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
